<template>
  <div class="venue-timeslot-container">
    <div class="page-header">
      <h2>场馆时间段管理</h2>
      <div class="header-actions">
        <el-date-picker
          v-model="selectedDate"
          type="date"
          placeholder="选择日期查看预订统计"
          @change="loadBookingStatistics"
          style="margin-right: 10px;"
        />
      <el-button @click="goBack">返回列表</el-button>
      </div>
    </div>
    
    <el-card shadow="never" v-loading="venueLoading">
      <template #header>
        <div class="card-header">
          <span>场馆信息</span>
        </div>
      </template>
      
      <el-descriptions :column="3" border>
        <el-descriptions-item label="场馆名称">{{ venueInfo.name }}</el-descriptions-item>
        <el-descriptions-item label="场馆类型">{{ getVenueTypeText(venueInfo.type) }}</el-descriptions-item>
        <el-descriptions-item label="营业时间">{{ venueInfo.open_time }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="venueInfo.status === 1 ? 'success' : 'info'">
            {{ venueInfo.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="地址">{{ venueInfo.address }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ venueInfo.contact_phone }}</el-descriptions-item>
      </el-descriptions>
    </el-card>
    
    <!-- 时间段管理 -->
    <el-card shadow="never" class="timeslot-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>时间段管理</span>
          <el-button type="primary" @click="handleAddSlot">新增时间段</el-button>
        </div>
      </template>
      
      <!-- 按星期几分组显示 -->
      <div class="day-filter">
        <el-radio-group v-model="currentDay" @change="filterByDay">
          <el-radio-button :label="0">全部</el-radio-button>
          <el-radio-button :label="1">周一</el-radio-button>
          <el-radio-button :label="2">周二</el-radio-button>
          <el-radio-button :label="3">周三</el-radio-button>
          <el-radio-button :label="4">周四</el-radio-button>
          <el-radio-button :label="5">周五</el-radio-button>
          <el-radio-button :label="6">周六</el-radio-button>
          <el-radio-button :label="7">周日</el-radio-button>
        </el-radio-group>
      </div>
      
      <el-table :data="filteredTimeSlots" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="星期" width="100">
          <template #default="scope">
            {{ getDayOfWeekText(scope.row.day_of_week) }}
          </template>
        </el-table-column>
        <el-table-column label="时间段" width="180">
          <template #default="scope">
            {{ scope.row.start_time }} - {{ scope.row.end_time }}
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="120">
          <template #default="scope">
            {{ scope.row.price }}元
          </template>
        </el-table-column>
        <el-table-column prop="capacity" label="容量" width="100" />
        <el-table-column label="预订人数" width="120">
          <template #default="scope">
            <span class="booking-count">{{ getBookingCount(scope.row.id) }}人</span>
          </template>
        </el-table-column>
        <el-table-column label="到场人数" width="120">
          <template #default="scope">
            <span class="attendance-count">{{ getAttendanceCount(scope.row.id) }}人</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '开放' : '关闭' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEditSlot(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDeleteSlot(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="filteredTimeSlots.length === 0" class="empty-data">
        <el-empty description="暂无时间段数据" />
      </div>
    </el-card>
    
    <!-- 添加/编辑时间段对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑时间段' : '新增时间段'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="slotFormRef"
        :model="slotForm"
        :rules="slotRules"
        label-width="100px"
      >
        <el-form-item label="星期" prop="day_of_week">
          <el-select v-model="slotForm.day_of_week" placeholder="请选择星期" style="width: 100%">
            <el-option v-for="i in 7" :key="i" :label="getDayOfWeekText(i)" :value="i" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="开始时间" prop="start_time">
          <el-time-picker
            v-model="timePickerValue.start"
            format="HH:mm"
            value-format="HH:mm"
            placeholder="请选择开始时间"
            @change="handleStartTimeChange"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="结束时间" prop="end_time">
          <el-time-picker
            v-model="timePickerValue.end"
            format="HH:mm"
            value-format="HH:mm"
            placeholder="请选择结束时间"
            @change="handleEndTimeChange"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="slotForm.price" :min="0" :precision="2" :step="10" style="width: 100%" />
        </el-form-item>
        
        <el-form-item label="容量" prop="capacity">
          <el-input-number v-model="slotForm.capacity" :min="1" :step="1" style="width: 100%" />
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="slotForm.status">
            <el-radio :label="1">开放</el-radio>
            <el-radio :label="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

export default {
  name: 'VenueTimeSlot',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const venueId = route.params.id
    
    // 场馆信息
    const venueLoading = ref(false)
    const venueInfo = reactive({})
    
    // 时间段列表
    const loading = ref(false)
    const timeSlots = ref([])
    const currentDay = ref(0) // 0表示全部
    
    // 预订统计相关
    const selectedDate = ref(new Date())
    const bookingStats = ref({})
    
    // 对话框相关
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const submitLoading = ref(false)
    const slotFormRef = ref(null)
    
    // 时间选择器值
    const timePickerValue = reactive({
      start: '',
      end: ''
    })
    
    // 表单数据
    const slotForm = reactive({
      id: null,
      day_of_week: 1,
      start_time: '',
      end_time: '',
      price: 0,
      capacity: 1,
      status: 1
    })
    
    // 表单验证规则
    const slotRules = {
      day_of_week: [
        { required: true, message: '请选择星期', trigger: 'change' }
      ],
      start_time: [
        { required: true, message: '请选择开始时间', trigger: 'change' }
      ],
      end_time: [
        { required: true, message: '请选择结束时间', trigger: 'change' }
      ],
      price: [
        { required: true, message: '请输入价格', trigger: 'blur' }
      ],
      capacity: [
        { required: true, message: '请输入容量', trigger: 'blur' }
      ]
    }
    
    // 场馆类型选项
    const venueTypes = [
      { label: '篮球场', value: 'basketball' },
      { label: '足球场', value: 'football' },
      { label: '网球场', value: 'tennis' },
      { label: '羽毛球馆', value: 'badminton' },
      { label: '游泳馆', value: 'swimming' },
      { label: '乒乓球室', value: 'pingpong' }
    ]
    
    // 获取场馆信息
    const fetchVenueInfo = async () => {
      venueLoading.value = true
      try {
        const token = localStorage.getItem('admin_token')
        const response = await request.get(`/v1/admin/venues/${venueId}`, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        Object.assign(venueInfo, response.data)
      } catch (error) {
        console.error('获取场馆信息失败', error)
        ElMessage.error('获取场馆信息失败: ' + (error.response?.data?.message || error.message))
      } finally {
        venueLoading.value = false
      }
    }
    
    // 获取时间段列表
    const fetchTimeSlots = async () => {
      loading.value = true
      try {
        const token = localStorage.getItem('admin_token')
        const response = await request.get(`/v1/admin/venues/${venueId}/time-slots`, {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        })
        timeSlots.value = response.data.timeSlots || []
      } catch (error) {
        console.error('获取时间段列表失败', error)
        ElMessage.error('获取时间段列表失败: ' + (error.response?.data?.message || error.message))
      } finally {
        loading.value = false
      }
    }
    
    // 加载预订统计
    const loadBookingStatistics = async () => {
      try {
        const dateStr = selectedDate.value ? 
          selectedDate.value.toISOString().split('T')[0] : 
          new Date().toISOString().split('T')[0]
        
        const token = localStorage.getItem('admin_token')
        const response = await fetch(`/api/v1/admin/venues/${venueId}/booking-statistics?date=${dateStr}`, {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
        })
        
        if (response.ok) {
          const data = await response.json()
          if (data.code === 200) {
            // 将统计数据按time_slot_id组织
            const statsMap = {}
            data.data.hourly_stats.forEach(stat => {
              statsMap[stat.time_slot_id] = {
                booked_count: stat.booked_count || 0,
                attended_count: stat.attended_count || 0
              }
            })
            bookingStats.value = statsMap
          } else {
            console.error('获取预订统计失败:', data.message)
            bookingStats.value = {}
          }
        } else {
          console.error('获取预订统计失败:', response.statusText)
          bookingStats.value = {}
        }
      } catch (error) {
        console.error('获取预订统计失败:', error)
        bookingStats.value = {}
      }
    }
    
    // 获取预订人数
    const getBookingCount = (timeSlotId) => {
      return bookingStats.value[timeSlotId]?.booked_count || 0
    }
    
    // 获取到场人数
    const getAttendanceCount = (timeSlotId) => {
      return bookingStats.value[timeSlotId]?.attended_count || 0
    }
    
    // 按星期几筛选
    const filterByDay = (day) => {
      currentDay.value = day
    }
    
    // 筛选后的时间段列表
    const filteredTimeSlots = computed(() => {
      if (currentDay.value === 0) {
        // 按星期几排序
        return [...timeSlots.value].sort((a, b) => {
          if (a.day_of_week !== b.day_of_week) {
            return a.day_of_week - b.day_of_week
          }
          return a.start_time.localeCompare(b.start_time)
        })
      } else {
        return timeSlots.value
          .filter(slot => slot.day_of_week === currentDay.value)
          .sort((a, b) => a.start_time.localeCompare(b.start_time))
      }
    })
    
    // 获取星期文本
    const getDayOfWeekText = (day) => {
      const dayMap = {
        1: '周一',
        2: '周二',
        3: '周三',
        4: '周四',
        5: '周五',
        6: '周六',
        7: '周日'
      }
      return dayMap[day] || day
    }
    
    // 获取场馆类型文本
    const getVenueTypeText = (type) => {
      const found = venueTypes.find(item => item.value === type)
      return found ? found.label : type
    }
    
    // 时间选择器变化处理
    const handleStartTimeChange = (val) => {
      slotForm.start_time = val
    }
    
    const handleEndTimeChange = (val) => {
      slotForm.end_time = val
    }
    
    // 添加时间段
    const handleAddSlot = () => {
      console.log('点击添加时间段')
      isEdit.value = false
      resetForm()
      dialogVisible.value = true
      console.log('对话框显示状态:', dialogVisible.value)
    }
    
    // 编辑时间段
    const handleEditSlot = (row) => {
      console.log('点击编辑时间段', row)
      isEdit.value = true
      resetForm()
      
      // 填充表单数据
      Object.assign(slotForm, {
        id: row.id,
        day_of_week: row.day_of_week,
        start_time: row.start_time,
        end_time: row.end_time,
        price: row.price,
        capacity: row.capacity,
        status: row.status
      })
      
      // 设置时间选择器的值
      timePickerValue.start = row.start_time
      timePickerValue.end = row.end_time
      
      dialogVisible.value = true
    }
    
    // 删除时间段
    const handleDeleteSlot = (row) => {
      ElMessageBox.confirm(`确认删除这个时间段吗？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const token = localStorage.getItem('admin_token')
          await request.delete(`/v1/admin/time-slots/${row.id}`, {
            headers: {
              'Authorization': `Bearer ${token}`
            }
          })
          ElMessage.success('删除成功')
          fetchTimeSlots() // 刷新列表
        } catch (error) {
          console.error('删除时间段失败', error)
          ElMessage.error('删除时间段失败: ' + (error.response?.data?.message || error.message))
        }
      }).catch(() => {})
    }
    
    // 重置表单
    const resetForm = () => {
      if (slotFormRef.value) {
        slotFormRef.value.resetFields()
      }
      
      Object.assign(slotForm, {
        id: null,
        day_of_week: 1,
        start_time: '',
        end_time: '',
        price: 0,
        capacity: 1,
        status: 1
      })
      
      timePickerValue.start = ''
      timePickerValue.end = ''
    }
    
    // 取消操作
    const handleCancel = () => {
      dialogVisible.value = false
      resetForm()
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!slotFormRef.value) return
      
      await slotFormRef.value.validate(async (valid) => {
        if (!valid) return
        
        submitLoading.value = true
        
        try {
          // 检查时间格式
          if (!slotForm.start_time || !slotForm.end_time) {
            ElMessage.error('请选择时间')
            submitLoading.value = false
            return
          }
          
          // 检查开始时间是否小于结束时间
          if (slotForm.start_time >= slotForm.end_time) {
            ElMessage.error('开始时间必须早于结束时间')
            submitLoading.value = false
            return
          }
          
          // 准备提交数据
          const data = {
            dayOfWeek: slotForm.day_of_week,
            startTime: slotForm.start_time,
            endTime: slotForm.end_time,
            price: slotForm.price,
            capacity: slotForm.capacity,
            status: slotForm.status
          }
          
          const token = localStorage.getItem('admin_token')
          const headers = {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
          }
          
          let response
          
          if (isEdit.value) {
            // 编辑
            response = await request.put(`/v1/admin/time-slots/${slotForm.id}`, data, { headers })
          } else {
            // 新增
            response = await request.post(`/v1/admin/venues/${venueId}/time-slots`, data, { headers })
          }
          
          ElMessage.success(isEdit.value ? '编辑成功' : '添加成功')
          dialogVisible.value = false
          fetchTimeSlots() // 刷新列表
          
        } catch (error) {
          console.error('保存时间段失败', error)
          ElMessage.error('保存时间段失败: ' + (error.response?.data?.message || error.message))
        } finally {
          submitLoading.value = false
        }
      })
    }
    
    // 返回列表页
    const goBack = () => {
      router.push('/venue/list')
    }
    
    onMounted(() => {
      console.log('组件挂载，场馆ID:', venueId)
      fetchVenueInfo()
      fetchTimeSlots()
      loadBookingStatistics()
    })
    
    return {
      venueLoading,
      venueInfo,
      loading,
      timeSlots,
      currentDay,
      dialogVisible,
      isEdit,
      submitLoading,
      slotFormRef,
      slotForm,
      slotRules,
      timePickerValue,
      filteredTimeSlots,
      selectedDate,
      bookingStats,
      handleAddSlot,
      handleEditSlot,
      handleDeleteSlot,
      handleCancel,
      filterByDay,
      getDayOfWeekText,
      getVenueTypeText,
      handleStartTimeChange,
      handleEndTimeChange,
      submitForm,
      goBack,
      loadBookingStatistics,
      getBookingCount,
      getAttendanceCount
    }
  }
}
</script>

<style lang="scss" scoped>
.venue-timeslot-container {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      font-size: 20px;
    }
    
    .header-actions {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .timeslot-card {
    margin-top: 20px;
  }
  
  .day-filter {
    margin-bottom: 20px;
  }
  
  .empty-data {
    padding: 30px 0;
  }
  
  .booking-count {
    color: #409eff;
    font-weight: bold;
  }
  
  .attendance-count {
    color: #67c23a;
    font-weight: bold;
  }
}
</style> 